<?php
/**
 * Description: 获取年终总结
 * User: devforma
 * Date: 16/1/19
 * Time: 11:05
 */

class GetQbSummary implements iController {

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        if (empty($queryArgs['user_id']))
            return genOutput(1000);

        if (($user = $this->getUserInfo($queryArgs['user_id']))) {
            if ($qbData = $this->getUserData($queryArgs['user_id'])) {
                $data = array();
                $data['enable_qb'] = true;

                $categoryNames = array(
                    1 => '判断推理',
                    2 => '数量关系',
                    3 => '资料分析',
                    4 => '常识判断',
                    5 => '言语理解与表达'
                );

                /** ------------------------------------------------------------------------------
                 * 第一页数据
                 */
                $data['nickname'] = empty($user->nickname) ? '匿名' : $user->nickname;

                if (empty($user->avatar)) {
                    $data['avatar'] = '';
                } elseif (strpos($user->avatar, 'http://') !== false) {
                    $data['avatar'] = $user->avatar;
                } else {
                    $data['avatar'] = 'http://edu.appublisher.com/user-images/avatar/'.$user->avatar;
                }

                //第一次使用时间
                $data['first_use_time'] = explode(' ', $qbData->create_time)[0];


                /** ------------------------------------------------------------------------------
                 * 第二页数据
                 */
                $allQuestions = $this->getHistoryQuestions($queryArgs['user_id']);
                if (empty($allQuestions)) {
                    return genOutput(1001);
                }

                //考试项目
                $data['first_exam'] = $this->getExamName($qbData->exam_detail_id);

                //第一道题目的知识点
                $noteList = getNotesByQuestions($allQuestions[0]->question_id);
                $data['first_note'] = $noteList[$allQuestions[0]->question_id]['name'];

                //第一次模考
                $mock = $this->getFirstPaper($queryArgs['user_id'], 8);
                if (!empty($mock)) {
                    $data['first_mock'] = array('name' => $mock->paper_title, 'score' => floatval($mock->evaluate));
                } else {
                    $data['first_mock'] = null;
                }

                /** ------------------------------------------------------------------------------
                 * 第三页数据
                 */
                $data['total_questions'] = intval($qbData->question_count);
                $data['accuracy'] = round($qbData->accuracy, 2);
                $data['learning_days'] = $this->getLearningDays($queryArgs['user_id']);


                /** ------------------------------------------------------------------------------
                 * 第四页数据
                 */
                $cats = array();
                $notes = array();
                $userAllNotes = array_keys(normalizeUserNoteInfo($qbData->note_info));
                $noteCount = 0;

                $qIds = array();
                foreach ($allQuestions as $q) {
                    if (!in_array($q->question_id, $qIds)) $qIds[] = $q->question_id;
                }
                $noteList = getNotesByQuestions($qIds);

                foreach ($allQuestions as $q) {
                    if (isset($cats[$q->category_id])) {
                        $cats[$q->category_id]['total']++;
                        if ($q->is_right) {
                            $cats[$q->category_id]['right']++;
                        }
                    } else {
                        $cats[$q->category_id] = array('total' => 1, 'right' => $q->is_right ? 1 : 0);
                    }

                    foreach ($noteList[$q->question_id]['id'] as $nid) {
                        if (!in_array($nid, $notes, true) && in_array($nid, $userAllNotes)) {
                            $noteCount++;
                            $notes[] = $nid;
                        }
                    }
                }

                $orderedCats = array();
                foreach ($cats as $index => $cat) {
                    $accu = round($cat['right'] / $cat['total'], 2);
                    $orderedCats["$accu"] = array('category_id' => $index, 'accu' => $accu);
                }
                krsort($orderedCats);

                $maxCat = array_shift($orderedCats);
                $data['max_category'] = array(
                    'name' => $categoryNames[$maxCat['category_id']],
                    'accuracy' => $maxCat['accu']
                );
                if (!empty($orderedCats)) {
                    $minCat = array_pop($orderedCats);
                    $data['min_category'] = array(
                        'name' => $categoryNames[$minCat['category_id']],
                        'accuracy' => $minCat['accu']
                    );
                } else {
                    $data['min_category'] = null;
                }

                $allNotesCount = count($userAllNotes);
                $data['note_percent'] = round($noteCount/$allNotesCount, 2);


                /** ------------------------------------------------------------------------------
                 * 第五页数据
                 */
                $data['score'] = intval($qbData->score);
                $data['rank'] = $this->getRank($qbData->score, $qbData->exam_detail_id);

                //宣言
                $xuanyan = $this->getXuanyan($queryArgs['user_id']);
                $data['xuanyan'] = !empty($xuanyan) ? $xuanyan : '';


                return genOutput(1, $data);
            } else {
                $data['enable_qb'] = false;

                /** ------------------------------------------------------------------------------
                 * 第一页数据
                 */
                $data['nickname'] = empty($user->nickname) ? '匿名' : $user->nickname;

                if (empty($user->avatar)) {
                    $data['avatar'] = '';
                } elseif (strpos($user->avatar, 'http://') !== false) {
                    $data['avatar'] = $user->avatar;
                } else {
                    $data['avatar'] = 'http://edu.appublisher.com/user-images/avatar/'.$user->avatar;
                }

                //第一次使用时间
                $data['first_use_time'] = explode(' ', $user->reg_time)[0];

                return genOutput(1, $data);
            }

        }

        return genOutput(1001);
    }

    private function getXuanyan($userId) {
        global $uddb;

        return $uddb->getVar('SELECT `xuanyan` FROM `user2016_xuanyan` WHERE `user_id`=:uid', [':uid' => $userId]);
    }


    private function getRank($score, $examDetailId) {
        global $cmsdb;

        $sql = "SELECT COUNT(*) FROM `qb_user_data` WHERE `exam_detail_id`={$examDetailId} AND `score`>{$score}
        UNION ALL SELECT COUNT(*) FROM `qb_user_data` WHERE `exam_detail_id`={$examDetailId}";

        $data = $cmsdb->getCol($sql);

        $rank = ($data[0]+1)/$data[1];
        if ($rank < 0.01)
            $rank = 0.01;

        return round($rank, 2);
    }

    private function getFirstPaper($userId, $paperType) {
        global $cmsdb;

        return $cmsdb->getRow('SELECT `paper_title`, `evaluate` FROM `qb_relationship_user_paper` WHERE `user_id`=:uid AND `paper_type`='.$paperType,
            array(':uid' => $userId));
    }

    private function getUserInfo($userId) {
        global $uddb;

        $data = $uddb->getRow('SELECT `ID`, `user_registered` FROM `user_auth_info` WHERE `ID`=:uid', array(':uid' => $userId));

        if (empty($data)) {
            return false;
        }

        $data2 = $uddb->getRow('SELECT `nickname`, `avatar` FROM `user_social_info` WHERE `user_id`=:uid',
            array(':uid' => $userId));

        if (empty($data2)) {
            return false;
        }

        $data2->reg_time = $data->user_registered;

        return $data2;
    }

    private function getExamName($examDetailId) {
        global $cmsdb;
        return $cmsdb->getVar('SELECT e.exam_name FROM `data_exams` AS e INNER JOIN `data_exam_detail` AS ed ON e.exam_id=ed.exam_id WHERE ed.id =:edid',
            array(':edid' => $examDetailId));
    }

    private function getHistoryQuestions($userId) {
        global $uddb;
        $tableName = $uddb->table($uddb->qbUserTests)->sublist($userId);

        return $uddb->getResults("SELECT `question_id`, `category_id`, `is_right` FROM `{$tableName}` WHERE `user_id`=:uid ORDER BY `id`", array(':uid' => $userId));
    }

    /**
     * 获取用户信息
     *
     * @param int $userId 用户id
     * @return mixed
     */
    private function getUserData($userId) {
        global $cmsdb;

        $cacheKey = 'qb_userData:'.$userId;
        if (($value = cacheGet($cacheKey)) != null) {
            return $value;
        } else {
            $value = $cmsdb->getRow('SELECT * FROM `qb_user_data` WHERE `user_id`=:user_id', array(':user_id' => $userId));
            if (!empty($value)) {
                cacheAdd($cacheKey, $value, 2*60*60); //2小时

                return $value;
            }
        }
        return null;
    }

    /**
     * 获取学习天数（有题目提交的日期才算）
     * @param int $userId 用户id
     * @return int
     */
    private function getLearningDays($userId) {
        global $cmsdb;
        $total = 0;

        $allRecords = $cmsdb->getCol("SELECT `action_time` FROM `qb_relationship_user_paper` WHERE `user_id`=:uid
        AND `status`=1", array(':uid' => $userId));

        if (empty($allRecords))
            return $total;

        $temp = array();
        foreach ($allRecords as $r) {
            $r2 = date('Y-m-d', strtotime($r));
            if (!isset($temp[$r2])) {
                $total++;
                $temp[$r2] = 0;
            }
        }

        return $total;
    }
}